/**
 * 文件中转站 - 前端JavaScript交互逻辑
 * 实现文件上传、下载、删除、搜索等功能
 */

class FileTransferStation {
    constructor() {
        // DOM元素引用
        this.dropZone = document.getElementById('dropZone');
        this.fileInput = document.getElementById('fileInput');
        this.selectFileBtn = document.getElementById('selectFileBtn');
        this.progressContainer = document.getElementById('progressContainer');
        this.progressFill = document.getElementById('progressFill');
        this.progressText = document.getElementById('progressText');
        this.filesContainer = document.getElementById('filesContainer');
        this.loadingSpinner = document.getElementById('loadingSpinner');
        this.refreshBtn = document.getElementById('refreshBtn');
        this.searchInput = document.getElementById('searchInput');
        this.totalFilesSpan = document.getElementById('totalFiles');
        this.toast = document.getElementById('toast');
        this.deleteModal = document.getElementById('deleteModal');
        this.fileDetailModal = document.getElementById('fileDetailModal');
        
        // 状态管理
        this.files = [];
        this.filteredFiles = [];
        this.currentDeleteFile = null;
        
        // 初始化应用
        this.init();
    }
    
    /**
     * 初始化应用程序
     */
    init() {
        this.bindEvents();
        this.loadFiles();
    }
    
    /**
     * 绑定事件监听器
     */
    bindEvents() {
        // 文件选择按钮点击事件
        this.selectFileBtn.addEventListener('click', () => {
            this.fileInput.click();
        });
        
        // 文件输入框变化事件
        this.fileInput.addEventListener('change', (e) => {
            this.handleFileSelect(e.target.files);
        });
        
        // 拖拽上传事件
        this.dropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            this.dropZone.classList.add('drag-over');
        });
        
        this.dropZone.addEventListener('dragleave', (e) => {
            e.preventDefault();
            this.dropZone.classList.remove('drag-over');
        });
        
        this.dropZone.addEventListener('drop', (e) => {
            e.preventDefault();
            this.dropZone.classList.remove('drag-over');
            this.handleFileSelect(e.dataTransfer.files);
        });
        
        // 点击拖拽区域选择文件
        this.dropZone.addEventListener('click', () => {
            this.fileInput.click();
        });
        
        // 刷新按钮事件
        this.refreshBtn.addEventListener('click', () => {
            this.loadFiles();
        });
        
        // 搜索输入框事件
        this.searchInput.addEventListener('input', (e) => {
            this.filterFiles(e.target.value);
        });
        
        // 删除确认对话框事件
        document.getElementById('cancelDeleteBtn').addEventListener('click', () => {
            this.hideDeleteModal();
        });
        
        document.getElementById('confirmDeleteBtn').addEventListener('click', () => {
            this.confirmDelete();
        });
        
        // 文件详情对话框关闭事件
        document.getElementById('closeDetailModal').addEventListener('click', () => {
            this.hideFileDetailModal();
        });
        
        // 点击模态框背景关闭
        this.deleteModal.addEventListener('click', (e) => {
            if (e.target === this.deleteModal) {
                this.hideDeleteModal();
            }
        });
        
        this.fileDetailModal.addEventListener('click', (e) => {
            if (e.target === this.fileDetailModal) {
                this.hideFileDetailModal();
            }
        });
        
        // ESC键关闭模态框
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                this.hideDeleteModal();
                this.hideFileDetailModal();
            }
        });
    }
    
    /**
     * 处理文件选择
     */
    handleFileSelect(files) {
        if (files.length === 0) return;
        
        // 依次上传每个文件
        Array.from(files).forEach((file, index) => {
            setTimeout(() => {
                this.uploadFile(file);
            }, index * 100); // 稍微延迟以避免并发问题
        });
    }
    
    /**
     * 上传文件
     */
    async uploadFile(file) {
        const formData = new FormData();
        formData.append('file', file);
        
        // 显示进度条
        this.showProgress();
        this.updateProgress(0, `正在上传 ${file.name}...`);
        
        try {
            const response = await fetch('/api/upload', {
                method: 'POST',
                body: formData
            });
            
            const result = await response.json();
            
            if (result.success) {
                this.showToast('success', `文件 "${file.name}" 上传成功！`);
                this.loadFiles(); // 重新加载文件列表
            } else {
                this.showToast('error', result.message);
            }
        } catch (error) {
            console.error('上传错误:', error);
            this.showToast('error', '上传失败，请检查网络连接');
        } finally {
            this.hideProgress();
            // 清空文件输入框
            this.fileInput.value = '';
        }
    }
    
    /**
     * 加载文件列表
     */
    async loadFiles() {
        this.showLoading();
        
        try {
            const response = await fetch('/api/files');
            const result = await response.json();
            
            if (result.success) {
                this.files = result.files;
                this.filteredFiles = [...this.files];
                this.renderFiles();
                this.updateTotalCount(result.total_count);
            } else {
                this.showToast('error', result.message);
                this.renderEmptyState();
            }
        } catch (error) {
            console.error('加载文件列表错误:', error);
            this.showToast('error', '加载文件列表失败');
            this.renderEmptyState();
        } finally {
            this.hideLoading();
        }
    }
    
    /**
     * 渲染文件列表
     */
    renderFiles() {
        if (this.filteredFiles.length === 0) {
            this.renderEmptyState();
            return;
        }
        
        const filesHtml = this.filteredFiles.map(file => {
            const fileIcon = this.getFileIcon(file.filename);
            const iconClass = this.getFileIconClass(file.filename);
            
            return `
                <div class="file-item" data-filename="${file.filename}">
                    <div class="file-icon ${iconClass}">
                        <i class="fas ${fileIcon}"></i>
                    </div>
                    <div class="file-info">
                        <div class="file-name" title="${file.filename}">${file.filename}</div>
                        <div class="file-meta">
                            <span><i class="fas fa-hdd"></i> ${file.size}</span>
                            <span><i class="fas fa-clock"></i> ${file.upload_time}</span>
                        </div>
                    </div>
                    <div class="file-actions">
                        <button class="btn btn-primary btn-sm" onclick="app.downloadFile('${file.filename}')">
                            <i class="fas fa-download"></i> 下载
                        </button>
                        <button class="btn btn-secondary btn-sm" onclick="app.showFileDetail('${file.filename}')">
                            <i class="fas fa-info-circle"></i> 详情
                        </button>
                        <button class="btn btn-danger btn-sm" onclick="app.showDeleteModal('${file.filename}')">
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </div>
                </div>
            `;
        }).join('');
        
        this.filesContainer.innerHTML = filesHtml;
    }
    
    /**
     * 渲染空状态
     */
    renderEmptyState() {
        const isEmpty = this.files.length === 0;
        const message = isEmpty ? '还没有上传任何文件' : '没有找到匹配的文件';
        const icon = isEmpty ? 'fa-folder-open' : 'fa-search';
        
        this.filesContainer.innerHTML = `
            <div class="empty-state">
                <i class="fas ${icon}"></i>
                <h3>${message}</h3>
                <p>${isEmpty ? '点击上方区域开始上传文件' : '尝试使用不同的搜索关键词'}</p>
            </div>
        `;
    }
    
    /**
     * 根据文件扩展名获取图标
     */
    getFileIcon(filename) {
        const ext = filename.toLowerCase().split('.').pop();
        
        // 图片文件
        if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'].includes(ext)) {
            return 'fa-file-image';
        }
        // 视频文件
        if (['mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv', 'webm'].includes(ext)) {
            return 'fa-file-video';
        }
        // 音频文件
        if (['mp3', 'wav', 'flac', 'aac', 'ogg', 'wma'].includes(ext)) {
            return 'fa-file-audio';
        }
        // 文档文件
        if (['doc', 'docx', 'pdf', 'txt', 'rtf'].includes(ext)) {
            return 'fa-file-alt';
        }
        // 表格文件
        if (['xls', 'xlsx', 'csv'].includes(ext)) {
            return 'fa-file-excel';
        }
        // 演示文件
        if (['ppt', 'pptx'].includes(ext)) {
            return 'fa-file-powerpoint';
        }
        // 压缩文件
        if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) {
            return 'fa-file-archive';
        }
        // 代码文件
        if (['js', 'html', 'css', 'py', 'java', 'cpp', 'c', 'php', 'rb'].includes(ext)) {
            return 'fa-file-code';
        }
        
        return 'fa-file';
    }
    
    /**
     * 获取文件图标样式类
     */
    getFileIconClass(filename) {
        const ext = filename.toLowerCase().split('.').pop();
        
        if (['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'].includes(ext)) {
            return 'image';
        }
        if (['mp4', 'avi', 'mkv', 'mov', 'wmv', 'flv', 'webm'].includes(ext)) {
            return 'video';
        }
        if (['mp3', 'wav', 'flac', 'aac', 'ogg', 'wma'].includes(ext)) {
            return 'audio';
        }
        if (['doc', 'docx', 'pdf', 'txt', 'rtf', 'xls', 'xlsx', 'csv', 'ppt', 'pptx'].includes(ext)) {
            return 'document';
        }
        if (['zip', 'rar', '7z', 'tar', 'gz'].includes(ext)) {
            return 'archive';
        }
        if (['js', 'html', 'css', 'py', 'java', 'cpp', 'c', 'php', 'rb'].includes(ext)) {
            return 'code';
        }
        
        return 'default';
    }
    
    /**
     * 过滤文件列表
     */
    filterFiles(searchTerm) {
        if (!searchTerm.trim()) {
            this.filteredFiles = [...this.files];
        } else {
            const term = searchTerm.toLowerCase();
            this.filteredFiles = this.files.filter(file => 
                file.filename.toLowerCase().includes(term)
            );
        }
        this.renderFiles();
    }
    
    /**
     * 下载文件
     */
    downloadFile(filename) {
        const link = document.createElement('a');
        link.href = `/api/download/${encodeURIComponent(filename)}`;
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        this.showToast('success', `开始下载 "${filename}"`);
    }
    
    /**
     * 显示删除确认对话框
     */
    showDeleteModal(filename) {
        this.currentDeleteFile = filename;
        document.getElementById('deleteFileName').textContent = filename;
        this.deleteModal.classList.add('show');
    }
    
    /**
     * 隐藏删除确认对话框
     */
    hideDeleteModal() {
        this.deleteModal.classList.remove('show');
        this.currentDeleteFile = null;
    }
    
    /**
     * 确认删除文件
     */
    async confirmDelete() {
        if (!this.currentDeleteFile) return;
        
        try {
            const response = await fetch(`/api/delete/${encodeURIComponent(this.currentDeleteFile)}`, {
                method: 'DELETE'
            });
            
            const result = await response.json();
            
            if (result.success) {
                this.showToast('success', `文件 "${this.currentDeleteFile}" 删除成功`);
                this.loadFiles(); // 重新加载文件列表
            } else {
                this.showToast('error', result.message);
            }
        } catch (error) {
            console.error('删除文件错误:', error);
            this.showToast('error', '删除文件失败');
        } finally {
            this.hideDeleteModal();
        }
    }
    
    /**
     * 显示文件详情
     */
    showFileDetail(filename) {
        const file = this.files.find(f => f.filename === filename);
        if (!file) return;
        
        const fileIcon = this.getFileIcon(filename);
        const iconClass = this.getFileIconClass(filename);
        
        document.getElementById('fileDetailContent').innerHTML = `
            <div style="text-align: center; margin-bottom: 2rem;">
                <div class="file-icon ${iconClass}" style="font-size: 4rem; margin-bottom: 1rem;">
                    <i class="fas ${fileIcon}"></i>
                </div>
                <h3 style="word-break: break-all;">${filename}</h3>
            </div>
            <div class="file-detail-info">
                <div style="display: grid; gap: 1rem;">
                    <div style="display: flex; justify-content: space-between; padding: 0.75rem; background: #f8fafc; border-radius: 6px;">
                        <span><i class="fas fa-file"></i> 文件名：</span>
                        <span style="font-weight: 500;">${filename}</span>
                    </div>
                    <div style="display: flex; justify-content: space-between; padding: 0.75rem; background: #f8fafc; border-radius: 6px;">
                        <span><i class="fas fa-hdd"></i> 文件大小：</span>
                        <span style="font-weight: 500;">${file.size}</span>
                    </div>
                    <div style="display: flex; justify-content: space-between; padding: 0.75rem; background: #f8fafc; border-radius: 6px;">
                        <span><i class="fas fa-clock"></i> 上传时间：</span>
                        <span style="font-weight: 500;">${file.upload_time}</span>
                    </div>
                    <div style="display: flex; justify-content: space-between; padding: 0.75rem; background: #f8fafc; border-radius: 6px;">
                        <span><i class="fas fa-tag"></i> 文件类型：</span>
                        <span style="font-weight: 500;">${filename.split('.').pop().toUpperCase()}</span>
                    </div>
                </div>
                <div style="margin-top: 2rem; display: flex; gap: 1rem; justify-content: center;">
                    <button class="btn btn-primary" onclick="app.downloadFile('${filename}')">
                        <i class="fas fa-download"></i> 下载文件
                    </button>
                    <button class="btn btn-danger" onclick="app.showDeleteModal('${filename}'); app.hideFileDetailModal();">
                        <i class="fas fa-trash"></i> 删除文件
                    </button>
                </div>
            </div>
        `;
        
        this.fileDetailModal.classList.add('show');
    }
    
    /**
     * 隐藏文件详情对话框
     */
    hideFileDetailModal() {
        this.fileDetailModal.classList.remove('show');
    }
    
    /**
     * 显示进度条
     */
    showProgress() {
        this.progressContainer.style.display = 'block';
    }
    
    /**
     * 隐藏进度条
     */
    hideProgress() {
        setTimeout(() => {
            this.progressContainer.style.display = 'none';
            this.updateProgress(0, '');
        }, 1000);
    }
    
    /**
     * 更新进度条
     */
    updateProgress(percent, text) {
        this.progressFill.style.width = `${percent}%`;
        this.progressText.textContent = text;
    }
    
    /**
     * 显示加载动画
     */
    showLoading() {
        this.loadingSpinner.style.display = 'flex';
    }
    
    /**
     * 隐藏加载动画
     */
    hideLoading() {
        this.loadingSpinner.style.display = 'none';
    }
    
    /**
     * 更新文件总数显示
     */
    updateTotalCount(count) {
        this.totalFilesSpan.textContent = `总文件数: ${count}`;
    }
    
    /**
     * 显示Toast消息
     */
    showToast(type, message) {
        this.toast.className = `toast ${type}`;
        this.toast.querySelector('.toast-message').textContent = message;
        this.toast.classList.add('show');
        
        // 3秒后自动隐藏
        setTimeout(() => {
            this.toast.classList.remove('show');
        }, 3000);
    }
}

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    // 创建全局应用实例
    window.app = new FileTransferStation();
    
    console.log('🚀 文件中转站前端已启动');
});

// 防止页面意外刷新时丢失上传进度
window.addEventListener('beforeunload', (e) => {
    const progressContainer = document.getElementById('progressContainer');
    if (progressContainer && progressContainer.style.display !== 'none') {
        e.preventDefault();
        e.returnValue = '文件正在上传中，确定要离开吗？';
        return e.returnValue;
    }
});

// 全局错误处理
window.addEventListener('error', (e) => {
    console.error('全局错误:', e.error);
});

// 处理未捕获的Promise拒绝
window.addEventListener('unhandledrejection', (e) => {
    console.error('未处理的Promise拒绝:', e.reason);
    e.preventDefault();
});